package com.flxz.user.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/Springai")
public class AiForwardController {

    @Value("${ai.alibaba.base-url:http://localhost:8090}")
    private String aiBaseUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    @GetMapping("/parse-transaction")
    public Map<String, Object> parseTransaction(@RequestParam("meg") String meg) throws URISyntaxException {
        // 转发到阿里云 AI 独立服务
        String url = aiBaseUrl + "/user/Springai/parse-transaction?meg=" + encode(meg);
        ResponseEntity<Map> resp = restTemplate.getForEntity(new URI(url), Map.class);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        // 兼容后端返回结构：如果独立服务外层同为 {code,msg,data}
        Object body = resp.getBody();
        if (body instanceof Map) {
            Map<?, ?> m = (Map<?, ?>) body;
            Object data = m.get("data");
            result.put("data", data != null ? data : m);
        } else {
            result.put("data", body);
        }
        return result;
    }

    private String encode(String s) {
        try {
            return java.net.URLEncoder.encode(s, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            return s;
        }
    }
}


